/*
 * 公共负载均衡api
 * */
#include <stdio.h>
#include "lb.h"

/*
 * 提供加权平均的负载均衡策略
 * weight		:数组,权重
 * num			:weight数组的大小
 * servs		:当前各个server被分配到的次数,该参数无需调用者关心,只需传一unsigned型数组即可(传入前需清零),数组长度为num
 * lb_strategy	:采用的负载均衡策略
 * return		:本次负载均衡选中的server的编号
 * */
int lb(const int *weight, int num, unsigned *servs, int lb_strategy)
{
	if (!servs)
		return -1;
	if (weight == NULL || lb_strategy == RRS) { //RRS
		unsigned t;
		for (int i = 1; i < num; i++) {
			if (servs[i - 1] > servs[i]) {
				t = servs[i];
				t++;
				if (t == 0) {
					t = 1;
					for (int j = i + 1; i < num; i++) {
						servs[j]  = 0;
					}
				}
				servs[i] = t;
				return i;
			}
		}
		t = servs[0];
		t++;
		if (t == 0) {
			t = 1;
			for (int i = 1; i < num; i++)
				servs[i] = 0;
		}
		servs[0] = t;
		return 0;
	}

	switch (lb_strategy)
	{
		//WRRS
		case WRRS:
			{
				/*
				 * WRRS尚未实现,暂时使用RRS代替
				for (int i = 0; i < num; i++) {
				}
				*/
				return lb(weight, num, servs, RRS);
			}
			break;
	}
	return 0;
}
